#import "HHListSheetAlertController.h"
#import "HHSheetAlertControllerAnimated.h"

#import <BCFoundation/BCFoundation.h>
#import <BCComConfigKit/BCComConfig.h>
#import <BCUIKit/BCUIKit.h>
#import <Masonry/Masonry.h>

@interface HHListSheetAlertController ()
<
    UITableViewDelegate,
    UITableViewDataSource,
    HHSheetAlertAnimatedController
>
/// 阴影
@property (nonatomic, strong) UIControl *shadeControl;
@property (nonatomic, strong) UIButton *closedBtn;
@property (nonatomic, strong) UILabel *titleLab;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation HHListSheetAlertController

///MARK: - system
- (instancetype)init {
    self = [super init];
    if (self) {
        self.modalPresentationStyle = UIModalPresentationCustom;
        self.transitioningDelegate = (id<UIViewControllerTransitioningDelegate>)self;
    }
    return self;
}

///MARK: - class public
+ (HHListSheetAlertController *)showAlertWithTitle:(NSString *)title list:(NSArray<NSString *> *)dataList completion:(void (^)(NSInteger index))completion {
    HHListSheetAlertController *alertController = [[HHListSheetAlertController alloc] init];
    alertController.title = title;
    alertController.dataArr = dataList;
    alertController.selectedBlock = completion;

    UIViewController *topPage = [UIApplication sharedApplication].keyWindow.rootViewController;
    [topPage presentViewController:alertController animated:YES completion:NULL];

    return alertController;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initializePageSubviews];
}

///MARK: - setter
- (void)setDataArr:(NSArray<NSString *> *)dataArr {
    _dataArr = dataArr;

    [self.tableView reloadData];
}

///MARK: - private
- (void)dismissSelfPage {
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)updateAlertContentLayout {
    if (!self.contentView.superview) {
        return;
    }
    if (self.dataArr.count < 1) {
        return;
    }
    CGFloat contentHeight = 57 + (self.dataArr.count * 56) + kBCScreenSafeFitBottom;
    // 设定最大值不超过屏幕-160
    contentHeight = MIN(kBCSCREEN_HEIGHT-160, contentHeight);

    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(contentHeight);
        make.height.mas_equalTo(contentHeight);
    }];
    [_shadeControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.contentView.mas_top);
    }];
}

///MARK: - Control
- (void)handleCancelButtonEvent:(id)sender {
    [self dismissSelfPage];
}

///MARK: - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(UITableViewCell.class)];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.font = BCComConfig.config.bcFont(16);
    cell.textLabel.textColor = BCComConfig.config.blackColor;
    cell.textLabel.text = [_dataArr bc_safeObjectAtIndex:indexPath.row];

    return cell;
}

///MARK: - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.selectedBlock) {
        self.selectedBlock(indexPath.row);
    }
    [self dismissSelfPage];
}
///MARK: - HHSheetAlertAnimatedController
- (UIView *)animateAlertView {
    return self.contentView;
}
///MARK: - UIViewControllerAnimatedTransitioning
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [[HHSheetAlertControllerAnimated alloc]init];
}

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return [[HHSheetAlertControllerAnimated alloc]init];
}

///MARK: - Page subviews
- (void)initializePageSubviews {
    self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6f];

    [self.view addSubview:self.shadeControl];
    [self.view addSubview:self.contentView];

    [self updateAlertContentLayout];

    UIView *headView = [[UIView alloc] init];
    [headView addSubview:self.titleLab];
    [headView addSubview:self.closedBtn];

    [self.contentView addSubview:headView];
    [self.contentView addSubview:self.tableView];

    // Constraints
    [headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(self.contentView);
        make.height.mas_equalTo(57);
    }];
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(headView);
    }];
    [_closedBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-5);
        make.centerY.mas_equalTo(headView);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(headView.mas_bottom);
        make.left.right.bottom.mas_equalTo(self.contentView);
    }];
}

///MARK: -getter
- (UIControl *)shadeControl {
    if (!_shadeControl) {
        _shadeControl = [[UIControl alloc] initWithFrame:self.view.bounds];
        [_shadeControl addTarget:self action:@selector(handleCancelButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _shadeControl;
}

- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBCSCREEN_WIDTH, 100)];
        _contentView.layer.masksToBounds = YES;
        _contentView.layer.cornerRadius = 12;
        _contentView.clipsToBounds = YES;
        _contentView.backgroundColor = [UIColor whiteColor];
    }
    return _contentView;
}

- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [UILabel bc_allocLable:^(UILabel *_Nonnull label) {
            label.font = BCComConfig.config.bcBoldFont(18);
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = BCComConfig.config.blackColor;
            label.text = self.title;
        }];
    }
    return _titleLab;
}

- (UIButton *)closedBtn {
    if (!_closedBtn) {
        @BCWeakify(self);
        _closedBtn = [UIButton bc_allocButton:^(UIButton *_Nonnull btn) {
            [btn setImage:[UIImage imageNamed:@"btn_sheet_alert_close"] forState:UIControlStateNormal];
        } action:^(UIButton *_Nonnull btn) {
            @BCStrongify(self);
            [self dismissSelfPage];
        }];
    }
    return _closedBtn;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.contentView.bounds style:UITableViewStyleGrouped];
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _tableView.separatorColor = kBCRGBColor(0xEFEFEF);
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.rowHeight = 56;
        _tableView.estimatedSectionHeaderHeight = 0.f;
        _tableView.estimatedSectionFooterHeight = 0.f;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass(UITableViewCell.class)];
        _tableView.bounces = NO;
        if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
            [_tableView setSeparatorInset:UIEdgeInsetsMake(0, 24, 0, 24)];
        }

        if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
            [_tableView setLayoutMargins:UIEdgeInsetsMake(0, 24, 0, 24)];
        }
        if (@available(iOS 11, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _tableView;
}

@end

